package cn.migu.music.hangupsms.service;

import cn.migu.music.cljz.keypress.api.model.PageRsp;
import cn.migu.music.common.exception.BusinessException;
import cn.migu.music.common.kafka.MiguKafkaTemplate;
import cn.migu.music.common.utils.LogUtils;
import cn.migu.music.hangupsms.common.config.HangUpSmsConfig;
import cn.migu.music.hangupsms.common.entity.ViewVrbtSettings;
import cn.migu.music.hangupsms.constants.EViewSmsType;
import cn.migu.music.hangupsms.model.ClSmsSettingParam;
import cn.migu.music.hangupsms.model.ViewVrbtSettingRefreshNotify;
import cn.migu.music.hangupsms.model.ViewVrbtSettingsDto;
import cn.migu.music.hangupsms.model.ViewVrbtSettingsPageReq;
import cn.migu.music.hangupsms.repository.ViewVrbtSettingsMapper;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 观看视频彩铃配置接口
 */
@Slf4j
@RestController
public class ViewVrbtSettingsService {
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private static final String            OPR_ADD             = "add";
    private static final String            OPR_UPDATE          = "update";
    private static final String            OPR_DELETE          = "delete";

    @Autowired
    private ViewVrbtSettingsMapper         viewVrbtSettingsMapper;

    @Autowired
    private MiguKafkaTemplate              miguKafkaTemplate;

    @Autowired
    private HangUpSmsConfig                hangUpSmsConfig;

    @Autowired
    private ViewVrbtSendMsgService         viewVrbtSendMsgService;

    /**
     * 新增观看视频彩铃配置接口
     * 
     * @param req
     *            请求参数
     */
    @PostMapping("/hangupsms/view-vrbt-config/add/v1.0")
    public void addViewVrbtConfig(@RequestBody ViewVrbtSettingsDto req) {
        List<ViewVrbtSettings> dataList = viewVrbtSettingsMapper.getByToneId(req.getToneId());
        if (!CollectionUtils.isEmpty(dataList)) {
            // 修改
            ViewVrbtSettings viewVrbtSettings = dataList.get(0);
            viewVrbtSettings.setProvinces(req.getProvinces());
            viewVrbtSettings.setViewSeconds(req.getViewSeconds());
            viewVrbtSettings.setCallingMsg(req.getCallingMsg());
            viewVrbtSettings.setMsgPort(req.getMsgPort());
            viewVrbtSettings.setLastOperator(req.getLastOperator());
            viewVrbtSettings.setOperateChannel(req.getOperateChannel());

            // 构建创蓝短信配置
            buildClSmsParam(req, viewVrbtSettings);

            viewVrbtSettingsMapper.update(viewVrbtSettings);
            // 刷新FLink 配置缓存
            sendRefreshKafka(OPR_UPDATE, req.getToneId(), req.getViewSeconds());
            // 删除redis缓存
            viewVrbtSendMsgService.deleteSettingCacheByToneId(req.getToneId());
        } else {
            // 新增
            ViewVrbtSettings newData = new ViewVrbtSettings();
            newData.setToneId(req.getToneId());
            newData.setProvinces(req.getProvinces());
            newData.setViewSeconds(req.getViewSeconds());
            newData.setCallingMsg(req.getCallingMsg());
            newData.setMsgPort(req.getMsgPort());
            newData.setLastOperator(req.getLastOperator());
            newData.setOperateChannel(req.getOperateChannel());
            // 构建创蓝短信配置
            buildClSmsParam(req, newData);

            viewVrbtSettingsMapper.insert(newData);
            // 刷新FLink 配置缓存
            sendRefreshKafka(OPR_ADD, req.getToneId(), req.getViewSeconds());
        }
    }

    /**
     * 修改观看视频彩铃配置接口
     * 
     * @param req
     *            请求参数
     */
    @PostMapping("/hangupsms/view-vrbt-config/update/v1.0")
    public void updateViewVrbtConfig(@RequestBody ViewVrbtSettingsDto req) {
        List<ViewVrbtSettings> dataList = viewVrbtSettingsMapper.getByToneId(req.getToneId());
        if (!CollectionUtils.isEmpty(dataList)) {
            // 修改
            ViewVrbtSettings viewVrbtSettings = dataList.get(0);
            viewVrbtSettings.setProvinces(req.getProvinces());
            viewVrbtSettings.setViewSeconds(req.getViewSeconds());
            viewVrbtSettings.setCallingMsg(req.getCallingMsg());
            viewVrbtSettings.setMsgPort(req.getMsgPort());
            viewVrbtSettings.setLastOperator(req.getLastOperator());
            viewVrbtSettings.setOperateChannel(req.getOperateChannel());
            // 构建创蓝短信配置
            buildClSmsParam(req, viewVrbtSettings);

            viewVrbtSettingsMapper.update(viewVrbtSettings);
            // 刷新FLink 配置缓存
            sendRefreshKafka(OPR_UPDATE, req.getToneId(), req.getViewSeconds());
            // 删除redis缓存
            viewVrbtSendMsgService.deleteSettingCacheByToneId(req.getToneId());
        } else {
            throw BusinessException.newInstance("数据不存在");
        }
    }

    /**
     * 删除观看视频彩铃配置接口
     * 
     * @param req
     *            请求参数
     */
    @PostMapping("/hangupsms/view-vrbt-config/del/v1.0")
    public void deleteViewVrbtConfig(@RequestBody ViewVrbtSettingsDto req) {
        viewVrbtSettingsMapper.delete(req.getToneId());
        // 刷新FLink 配置缓存
        sendRefreshKafka(OPR_DELETE, req.getToneId(), req.getViewSeconds());
        // 删除redis缓存
        viewVrbtSendMsgService.deleteSettingCacheByToneId(req.getToneId());
    }

    /**
     * 分页查询观看视频彩铃配置接口
     * 
     * @param req
     *            请求参数
     * @return 分页数据
     */
    @PostMapping("/hangupsms/view-vrbt-config/list/v1.0")
    public PageRsp<ViewVrbtSettingsDto> queryViewVrbtConfigList(@RequestBody ViewVrbtSettingsPageReq req) {
        int start = (req.getPageIndex() - 1) * req.getPageSize();
        int size = req.getPageSize();
        PageRsp<ViewVrbtSettingsDto> result = new PageRsp<>();
        int count = viewVrbtSettingsMapper.countByCondition(req.getToneId());
        result.setTotalElements(count);
        if (count <= 0) {
            return result;
        }
        List<ViewVrbtSettings> content = viewVrbtSettingsMapper.getByConditionByPage(req.getToneId(), start,
            size);
        if (!CollectionUtils.isEmpty(content)) {
            List<ViewVrbtSettingsDto> data = content.stream().map(p -> {
                ViewVrbtSettingsDto dto = new ViewVrbtSettingsDto();
                dto.setToneId(p.getToneId());
                dto.setProvinces(p.getProvinces());
                dto.setViewSeconds(p.getViewSeconds());
                dto.setCallingMsg(p.getCallingMsg());
                dto.setMsgPort(p.getMsgPort());
                dto.setLastOperator(p.getLastOperator());
                dto.setOperateChannel(p.getOperateChannel());
                if (p.getCreateTime() != null) {
                    dto.setCreateTime(p.getCreateTime().format(DATE_TIME_FORMATTER));
                }

                if (p.getUpdateTime() != null) {
                    dto.setUpdateTime(p.getUpdateTime().format(DATE_TIME_FORMATTER));
                }

                // 创蓝配置，从数据库取出转换
                if (StringUtils.equalsAny(p.getMsgPort(), EViewSmsType.CL_SMS.getCode(), EViewSmsType.CL_VMS.getCode())) {
                    ClSmsSettingParam clSmsSettingParam = JSON.parseObject(p.getCallingMsg(), ClSmsSettingParam.class);
                    dto.setMsgPort(null);
                    dto.setCallingMsg(null);
                    String smsType = EViewSmsType.valueOfCode(p.getMsgPort()).getType();
                    dto.setSmsType(smsType);
                    dto.setTemplateId(clSmsSettingParam.getTemplateId());
                    dto.setBusinessId(clSmsSettingParam.getBusinessId());
                } else {
                    String smsType = EViewSmsType.DEFAULT.getType();
                    dto.setSmsType(smsType);
                }

                return dto;
            }).collect(Collectors.toList());
            result.setContent(data);
        }

        return result;
    }

    /**
     * 通知流式计算平台，刷新配置
     * 
     * @param action
     * @param ringId
     * @param minDuration
     */
    public void sendRefreshKafka(String action, String ringId, Long minDuration) {
        try {
            ViewVrbtSettingRefreshNotify event = new ViewVrbtSettingRefreshNotify();
            event.setAction(action);
            event.setRingId(ringId);
            if (minDuration != null) {
                event.setMinDuration(minDuration * 1000);
            }
            miguKafkaTemplate.send(hangUpSmsConfig.getViewVrbtSettingRefreshTopic(), JSON.toJSONString(event));
        } catch (Exception ex) {
            LogUtils.error(ex, log, "发kafka刷新配置异常");
        }
    }

    private void buildClSmsParam(ViewVrbtSettingsDto req, ViewVrbtSettings viewVrbtSettings) {
        if (StringUtils.equalsAny(req.getSmsType(), EViewSmsType.CL_SMS.getType(), EViewSmsType.CL_VMS.getType())) {
            // 创蓝短信配置,入库保存转换
            ClSmsSettingParam clSmsSettingParam = new ClSmsSettingParam();
            clSmsSettingParam.setTemplateId(req.getTemplateId());
            clSmsSettingParam.setBusinessId(req.getBusinessId());
            String smsCode = EViewSmsType.valueOfType(req.getSmsType()).getCode();
            viewVrbtSettings.setMsgPort(smsCode);
            viewVrbtSettings.setCallingMsg(JSON.toJSONString(clSmsSettingParam));
        }
    }
}
